<?php

class IssueController extends Controller
{
  public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the register page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xCCCCCC,
				'minLength'=>7
			),
		);
	}
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('submit','captcha','check','admin'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
 	/**
 	* Check page. 
 	*/
	public function actionCheck()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('check',array(
			'model'=>$model,
		));
	} 
		
	
	/**
	 * Submit Issue.
	 */
	public function actionSubmit()
	{
		$model=new Issue;

		if(isset($_POST['Issue']))
		{
			$model->attributes=$_POST['Issue'];	
			$model->userID = Yii::app()->user->id;
			$model->gradeID = $_POST['Issue']['gradeID'];
			$model->subjectID = $_POST['Issue']['subjectID'];
			$model->quantity_object = $_POST['Issue']['quantity_object'];
			
		  $imgs = CUploadedFile::getInstances($model,"image"); // o cho nay, no lay dc images object roi		  
			$errors = array();
			$list_file = array();
			if(!empty($imgs)) {
				foreach ($imgs as $key=>$img) {
					//$model->image = CUploadedFile::getInstance($model,"image[$key]");
					$list_file[] = $model->image; 
			    /*if(!$model->validate()) {
			    	$errors[] = $model->getErrors("image");
			    }*/
				}
			}		  
		  
			$validate1 = $model->validate(array('gradeID','subjectID','content'));
			 
			if($validate1 && empty($errors) && !empty($list_file)) {	   
				
				$checkerID = $model->getChecker();
				if($checkerID!=0) {
					$model->status = 21;
					$model->resolver = $checkerID; 
					$user_status = UserStatus::model()->findByAttributes(array('userID'=>$checkerID));
					if(!empty($user_status))
					{
						$user_status->statusID = 3;
						$user_status->update();
					}
				}		
				else {
					$model->status = 20;
				}				
				if($model->save(false)) {
					if(!empty($imgs)) {
						foreach ($imgs as $img) {
							$file=new File();
							$file->filename = $img->getName();
				    	$file->filesaved = encodeFilename(time().'_'.$img->getName());
				    	$file->filetype = 'image';
				    	$file->folder = 'issues';
				    	$file->save(false);
				    	$img->saveAs('upload/issues/'.$file->filesaved);
							$fileID =  $file->ID;
							$file_issue = new FileIssue();
							$file_issue->issueID = $model->ID;
							$file_issue->fileID = $file->ID; 
							$file_issue->save(false);
						}
					}
				}	
				
				//validate the upload file
				
				
				//save file to the upload path
				
				
				Yii::app()->user->setFlash('success',"Submit thanh cong.");
				$this->refresh();
			}	
			else {
				if(empty($list_file)) {
					$model->addError('image', 'Chon file nha.');
				}
				if(!empty($errors)) {
					foreach ($errors as $err) {
						foreach ($err as $val) {
							$model->addError('image', $val);
						}
					}
				}
			}
		}
		$this->render('submit',array(
			'model'=>$model,
		));
	}
	
	
	/**
	 *  
	 */
	public function actionAdmin()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}		
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Issue::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='issue-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
